package com.sosolabs.com.site.client.view;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SelectionCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.sosolabs.com.site.client.presenter.CellTablePresenter;


public class CellSampleView extends Composite implements CellTablePresenter.Display {

	@UiTemplate("ui/CellSampleView.ui.xml")
	interface Binder extends UiBinder<Widget, CellSampleView> {
	}

	private static Binder binder = GWT.create(Binder.class);

	@UiField
	Button confirmButton;

	@UiField
	CellTable<Contact> cellTable;
	
	@UiField
	SimplePager simplePager;
	
	ListDataProvider<String> dataProvider;
	
	@UiFactory SimplePager mSimplePager(){
		SimplePager.Resources pagerResources = GWT.create( SimplePager.Resources.class);
		simplePager = new SimplePager(
		TextLocation.CENTER, pagerResources, false, 0, true);
		simplePager.setDisplay(cellTable);
		return simplePager;
	}
	
	@UiFactory CellTable<Contact> makeCellTable() {
		final ListDataProvider<Contact> dataProvider = new ListDataProvider<Contact>();		
		List<Contact> contacts = dataProvider.getList();
		contacts.addAll(CONTACTS);
		
		//CellTable<Contact> 
		cellTable = new CellTable<Contact>(/*Contact.KEY_PROVIDER*/);
		cellTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);

	    // Add a text column to show the name.
	    TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
	      @Override
	      public String getValue(Contact object) {
	        return object.name;
	      }
	    };
	    cellTable.addColumn(nameColumn, "Name");

	    // Add a date column to show the birthday.
	    DateCell dateCell = new DateCell();
	    Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) {
	      @Override
	      public Date getValue(Contact object) {
	        return object.birthday;
	      }
	    };
	    cellTable.addColumn(dateColumn, "Birthday");

	    // Add a text column to show the address.
	    TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
	      @Override
	      public String getValue(Contact object) {
	        return object.address;
	      }
	    };
	    cellTable.addColumn(addressColumn, "Address");
	    
	    Column<Contact,String> firstNameColumn = new Column<Contact, String>(new EditTextCell()) {
	        @Override
	  		      public String getValue(Contact object) {
	  		        return object.name+object.address;
	  		      }
	  	    };
	  	  cellTable.addColumn(firstNameColumn, "add");	 
	  	firstNameColumn.setFieldUpdater(new FieldUpdater<Contact, String>() {
	        public void update(int index, Contact object, String value) {
	          // Called when the user changes the value.
	          object.address = value;
	          
	          dataProvider.refresh();
	          
	          //ContactDatabase.get().refreshDisplays();
	        }
	      });

	  	 final MultiSelectionModel<Contact> mselectionModel = new MultiSelectionModel<Contact>();
		    cellTable.setSelectionModel(mselectionModel);
		    mselectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
		      public void onSelectionChange(SelectionChangeEvent event) {
		    	  CheckboxCell checkb = (CheckboxCell) event.getSource();
		    	 // boolean b = mselectionModel.isSelected(checkb);
		    	  if(true)//checkb.getValue())
		    	  {
			        Set<Contact> selected = mselectionModel.getSelectedSet();
			        if (selected != null) {
			        	Iterator iter = selected.iterator();
			        	while(iter.hasNext())
			        		Window.alert(((Contact)(iter.next())).name);
			          //Window.alert("You selected: " + selected.name);
			        }
		    	  }
		      }
		    });
		    
	  	Column<Contact, Boolean> mcheckColumn = new Column<Contact, Boolean>(
	  	        new CheckboxCell(true)) {
	  	      @Override
	  	      public Boolean getValue(Contact object) {
	  	        // Get the value from the selection model.
	  	    	  //Window.alert(object.name);
	  	        return mselectionModel.isSelected(object);
	  	      }
	  	    };
	  	    mcheckColumn.setFieldUpdater(new FieldUpdater<Contact, Boolean>() {
	  	      public void update(int index, Contact object, Boolean value) {
	  	        // Called when the user clicks on a checkbox.
	  	        mselectionModel.setSelected(object, value);
	  	      }
	  	    });
	  	  cellTable.addColumn(mcheckColumn, SafeHtmlUtils.fromSafeConstant("<br>"));
	  	  
	  	final List<String> lis = new ArrayList<String>();
	  	lis.add("Jan");
	  	lis.add("feb");
	  	lis.add("Mar");
	  	SelectionCell categoryCell = new SelectionCell(lis);
	    Column<Contact, String> categoryColumn = new Column<
	    Contact, String>(categoryCell) {
	      @Override
	      public String getValue(Contact object) {
	        return object.address;
	      }
	    };
	    cellTable.addColumn(categoryColumn, "month");
	    categoryColumn.setFieldUpdater(new FieldUpdater<Contact, String>() {
	      public void update(int index, Contact object, String value) {
	        for (String category : lis) {
	          if (category.equals(value)) {
	            object.address = category;
	            dataProvider.refresh();
	          }
	        }
	      }
	    });
	    
	    dataProvider.addDataDisplay(cellTable);	 
		return cellTable;
	}
	
	private static class Contact {
	    private String address;
	    private final Date birthday;
	    private final String name;
	    private static int nextid = 0;
	    private final int id;

	    public Contact(String name, Date birthday, String address) {
	    	this.id = nextid;
	    	nextid++;
	      this.name = name;
	      this.birthday = birthday;
	      this.address = address;
	    }
	    
	    private int getId()
	    {
	    	return this.id;
	    }
	   
	  }

	  /**
	   * The list of data to display.
	   */
	  private static final List<Contact> CONTACTS = Arrays.asList(
	      new Contact("John", new Date(80, 4, 12), "123 Fourth Avenue"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
	      new Contact("George", new Date(46, 6, 6), "1600 Pennsylvania Avenue"));
	  

	public CellSampleView() {
		initWidget(binder.createAndBindUi(this));
	}
	
	public HasClickHandlers getConfirmButton() {
		return confirmButton;
	}
	
	public Widget asWidget() {
		return this;
	}	
}
